import {
  Controller,
  Get,
  Post,
  Delete,
  Param,
  Body,
  Patch,
  Query,
  DefaultValuePipe,
  ParseIntPipe
} from '@nestjs/common';
import { CategoryService, PaginatedCategoryPages } from './category.service';
import { Category } from './category.entity';

@Controller('category')
export class CategoryController {
  constructor(
    private readonly categoryService: CategoryService
  ) { }

  // 添加类别（后台）
  @Post('add')
  async create(
    @Body('name') name: string,
    @Body('coverImg') coverImg?: string,
    @Body('description') description?: string,
    @Body('images') images?: Record<string, any>,
    @Body('coverImg') is_visible?: boolean,
  ): Promise<Category> {
    return this.categoryService.createCategory(name, coverImg, description, images, is_visible);
  }

  @Post('/update')
  async update(
    @Body()
    updates: {
      id: number;
      name?: string;
      coverImg?: string;
      description?: string;
      images?: Array<Record<string, any>>;
      is_visible?: boolean;
    },
  ): Promise<Category> {
    return this.categoryService.updateCategory(updates.id, updates);
  }

  // 删除类别（后台）
  @Delete('delete/:id')
  async delete(@Param('id') id: number): Promise<void> {
    return this.categoryService.deleteCategory(id);
  }


  // 切换显示状态（后台）
  @Post('/toggle-visibility')
  async toggleVisibility(@Body() body: { id: number, visible: boolean }): Promise<Category> {
    // console.log(body.id, body.visible, 'body.id, body.visible==');
    return this.categoryService.toggleVisibility(body.id, body.visible);
  }

  // 获取所有类别
  @Get('all')
  async getAllCategories(
    @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number = 1,
    @Query('limit', new DefaultValuePipe(10), ParseIntPipe) limit: number = 10,
  ): Promise<PaginatedCategoryPages> {
    limit = Math.min(limit, 100);
    return this.categoryService.getAllCategories(page, limit);
  }

  // 获取可见类别（供前端调用）
  @Get()
  async getVisible(): Promise<Category[]> {
    return this.categoryService.getVisibleCategories();
  }

  @Get(':id')
  async getCategory(@Param('id') id: number): Promise<Category> {
    return this.categoryService.getCategoryById(id);
  }
}
